package com.hanson.comparator;

import com.hanson.utils.Chinese2PinYinUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.Comparator;

/**
 * @description: 字符串比较器
 * @classname: StringComparator
 * @author: HansonLee
 * @create: 2022/09/14
 **/
public class StringComparator implements Comparator<String> {

    @Override
    public int compare(String o1, String o2) {
        //转拼音
        String oo1 = Chinese2PinYinUtil.convert(o1,true);
        String oo2 = Chinese2PinYinUtil.convert(o2,true);
        if (StringUtils.isBlank(oo1) && StringUtils.isBlank(oo2)) return 0;
        if (StringUtils.isBlank(oo1)) return -oo2.length();
        if (StringUtils.isBlank(oo2)) return oo1.length();
        if (oo1.length() == oo2.length()){
            char[] a1 = oo1.toCharArray();
            char[] a2 = oo2.toCharArray();
            for (int i = 0; i < a1.length; i++) {
                if (a1[i] - a2[i] == 0){
                    continue;
                }
                return a1[i] - a2[i];
            }
            return 0;
        }
        return oo1.length() - oo2.length();
    }
}
